package com.qkjia.day03;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class Test06_ForkJoin {
    public static void main(String[] args) throws Exception {
        MyTask myTask = new MyTask(0, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        System.out.println(forkJoinTask.get());
    }
}
class MyTask extends RecursiveTask<Integer>{
    public static final int THRESHOLD=10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }
    //用于计算小任务的方法
    @Override
    protected Integer compute() {
        //如果end-begin<=阈值 就不能再拆分成小任务
        if((end-begin)<=THRESHOLD){
            for (int i = begin; i <= end; i++) {
                result+=i;
            }
        }else{
            //得到中间值
           int mid=(begin+end)/2;
           //划分为小任务
            MyTask myTask1 = new MyTask(begin, mid);
            MyTask myTask2 = new MyTask(mid+1, end);
            //分配成小任务各自执行
            myTask1.fork();
            myTask2.fork();
            result=myTask1.join()+myTask2.join();
        }
        return result;
    }
}
